import { _decorator, Component, Node, Prefab, instantiate, director, PhysicsSystem2D, Contact2DType, Collider2D, IPhysics2DContact, resources, SpriteFrame, Sprite } from 'cc';
import { bullet } from './bullet';
import { enemy } from './enemy';
const { ccclass, property } = _decorator;

@ccclass('player')
export class player extends Component {
	@property(Prefab)
	bulletPre:Prefab = null
    start() {
		PhysicsSystem2D.instance?.on(
			Contact2DType.BEGIN_CONTACT,
			this.onBeginContact,
			this
		);
		// 移动
		this.node.on(Node.EventType.TOUCH_MOVE,(e)=>{
			this.node.setPosition(
				e.getLocation().x-228.5,
				e.getLocation().y-404.179)
		})
		// 攻击
		this.schedule(()=>{
			// 创建子弹
			let bullet = instantiate(this.bulletPre)
			bullet.setParent(director.getScene().getChildByName('Canvas')) 
			bullet.setPosition(this.node.getPosition().x, this.node.getPosition().y+80)
		},0.35)
		
    }
	onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D) {
		if ((selfCollider.tag === 0 && otherCollider.tag === 1) ||
			(selfCollider.tag === 1 && otherCollider.tag === 0)) {
			selfCollider.tag === 0
				? selfCollider.getComponent(bullet).miss()
				: selfCollider.getComponent(enemy).die();
			otherCollider.tag === 1
				? otherCollider.getComponent(enemy).die()
				: otherCollider.getComponent(bullet).miss();
		}
		if ((selfCollider.tag === 3 || otherCollider.tag === 3)) {
			resources.load('hero1_die/spriteFrame', SpriteFrame, (err, data) => {
				this.node.getComponent(Sprite).spriteFrame = data
			})
			setTimeout(() => {
				this.node?.destroy();
			}, 500)
		}
	}
    update(deltaTime: number) {
        
    }
}

